package com.zghhost.codedemo.stock;

import com.zghhost.codedemo.util.IOUtil;
import com.zghhost.codedemo.util.PatternUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/4/26 13:47
 */
public class StockHelloWorld {
    private static String url = "http://quotes.money.163.com/service/chddata.html?code=%s&start=%s&end=%s";

    private static int lastNYear = 1;

    //沪0开头 深1开头 +6位代码
    private static String code = "0"+600545;

    public static void main(String[] args)throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        String end = sdf.format(c.getTime());
        c.add(Calendar.YEAR,0-lastNYear);
        String start = sdf.format(c.getTime());

        List<String[]> data = new ArrayList<String[]>();
        BufferedReader br = new BufferedReader(new InputStreamReader(download(String.format(url,code,start,end)),"gb2312"));
        String line = null;
        while((line = br.readLine()) != null){
            data.add(Arrays.copyOf (line.split(","),30));
        }
        data.remove(0);

        //下标16开始我可以放东西
        int i=-1;
        for(String[] props : data){
            //当前处理的行 i
            i++;

//            props[16] = getAvg(data,i,6,10);
//            props[17] = props[6];
//
//            props[18] = getAvg(data,i,11,10);
//            props[19] = getAvg(data,i,14,10);

            props[16] = divide(props[14],props[3]);
            props[17] = divide(props[13],props[3]);
            props[18] = getBaiduItemCount(props[2],props[0],10);
            try{
                props[19] = divide(props[18],"10");
            }catch (Exception e){}
            System.out.println(Arrays.toString(props));
        }
    }

    /**
     * 获取过去一段时间的平均值
     * @param data
     * @param y
     * @param daycnt
     * @return
     */
    public static String getAvg(List<String[]> data,int x,int y,int daycnt){
        Double total = 0D;
        for(int i=0;i<daycnt;i++){
            int row = x+i+1;
            if(data.size() > row){
                total += Double.valueOf(data.get(row)[y]);
            }
        }
        Double avgval = total / daycnt;
        return new java.text.DecimalFormat("#.00").format(avgval);
    }

    public static String divide(String dividend,String divisor){
        try{
            return String.valueOf(new BigDecimal(dividend).divide(new BigDecimal(divisor),2));
        }catch (Exception e){
//            throw new RuntimeException("想要计算"+dividend+"/"+divisor+" 除数不能为0");
            return "0";
        }
    }

    public static InputStream download(String url)throws Exception{
//        System.out.println("当前地址："+url);
        URL rl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)rl.openConnection();
        conn.setRequestProperty("Accept"," text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
        conn.setRequestProperty("Accept-Language"," zh-CN,zh;q=0.9,en;q=0.8");
        conn.setRequestProperty("Cache-Control"," max-age=0");
        conn.setRequestProperty("Connection"," keep-alive");
        conn.setRequestProperty("Cookie"," _ntes_nuid=275a996b6251b11ae2753893106e8ca5; _ntes_nnid=14f4aa92652be206885b64cdca6f9eff,1540257387975; vjuids=3dc568a59.167ceabf85a.0.6332ccf32ed4e; s_n_f_l_n3=4588548c047f965d1545360636025; _antanalysis_s_id=1545360636172; ne_analysis_trace_id=1545881326551; starttime=; df=mail163_letter; mail_psc_fingerprint=63e5d0f12abcedc6013c96733dbae61c; usertrack=CrHtf1xBaD06H4FZAwVXAg==; mail_login_way=normal; NTES_SESS=waR28eDqQda8QsX1AFRH4Dt7ccf.nCawRb4rgxpGPo9RBlf2BpU6VjEgQIVsFXx1rXMEL_xjrrH0sShaR2ODTJfrczMpt6e4qecKKwggl32zJFv5jxqlCyb1.bG6KbwpVflrfm7McDNpoOnDDcFt32W.lttznWyRkM.tZGwZ5dVa1wEIS5zLbqmmGwN5t8Tro; P_INFO=zghhost@163.com|1553761305|0|mail163|00&99|bej&1553740664&note_client#bej&null#10#0#0|&0|neteasesnailreader&note_client|zghhost@163.com; nts_mail_user=zghhost@163.com,-1,1; vjlast=1545360636.1556256525.21; vinfo_n_f_l_n3=4588548c047f965d.1.0.1545360636024.0.1556258351283");
        conn.setRequestProperty("Host"," quotes.money.163.com");
        conn.setRequestProperty("Referer"," http://quotes.money.163.com/");
        conn.setRequestProperty("Upgrade-Insecure-Requests"," 1");
        conn.setRequestProperty("User-Agent"," Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36");
        return conn.getInputStream();
    }

    public static String getBaiduItemCount(String name,String day,int daynum)throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date thatDate = sdf.parse(day);
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(thatDate);
        c.add(Calendar.DATE,-1);
        c.set(Calendar.HOUR_OF_DAY,23);
        c.set(Calendar.MINUTE,59);
        c.set(Calendar.SECOND,59);
//        System.out.print(name+"  ");
//        System.out.print(sdf.format(c.getTime())+"  ");
        long ets = c.getTime().getTime()/1000;
        c.add(Calendar.DATE,1-daynum);
        c.set(Calendar.HOUR_OF_DAY,0);
        c.set(Calendar.MINUTE,0);
        c.set(Calendar.SECOND,0);
//        System.out.println(sdf.format(c.getTime()));
        long sts = c.getTime().getTime()/1000;
        String url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd="+ URLEncoder.encode(name,"utf8") +"&gpc=stf%3D"+sts+"%2C"+ets+"%7Cstftype%3D2";
//        System.out.println(url);

        String baidures = IOUtil.is2str(download(url),true);

        String bdcnt = PatternUtil.getValueWithRex(baidures,"百度为您找到相关结果约(.*)个",1);
        return bdcnt.replaceAll(",","");
    }

//    public static void list2file()
}
